package service

import (
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"github.com/ngaut/log"
	"sort"
	"github.com/shopspring/decimal"
)

type TrustItem struct {
	Number string `json:"n"`
	Price  decimal.Decimal `json:"p"`
}

type TrustItemForReturn struct {
	Number string `json:"n"`
	Price  string `json:"p"`
}

func GetTrustList(conn redis.Conn, trustType, key string, floatPrice int) []TrustItemForReturn {

	values, err := redis.Values(conn.Do("LRANGE", key, 0, -1))
	if err != nil {
		log.Errorf("get depth error, key:%s, msg: %s", key, err.Error())
		return nil
	}

	var items = make([]string, 0)
	redis.ScanSlice(values, &items)

	var trustItems = make([]TrustItem, 0)
	for _, item := range items {
		var v TrustItem
		if err := json.Unmarshal([]byte(item), &v); err != nil {
			log.Errorf("json unmarshal depth trust item error, msg: %s", err.Error())
			continue
		}
		trustItems = append(trustItems, v)
	}

	// 买单从高到低
	if trustType == "buy" {
		sort.Slice(trustItems, func(i, j int) bool {
			return trustItems[i].Price.GreaterThan(trustItems[j].Price)
		})
	} else {
		sort.Slice(trustItems, func(i, j int) bool {
			return trustItems[i].Price.GreaterThan(trustItems[j].Price)
		})
	}

	results := make([]TrustItemForReturn, 0)
	for _, v := range trustItems {
		results = append(results, TrustItemForReturn{
			Number: 	v.Number,
			Price: 		v.Price.StringFixedBank(int32(floatPrice)),
		})
	}

	return results
}